//
//  Status.swift
//  WeiBo001
//
//  Created by Zhanghong on 15/7/1.
//  Copyright © 2015年 HeiMa. All rights reserved.
//

import UIKit
import SDWebImage

private let WB_Home_Timeline_URL = "2/statuses/home_timeline.json"

class Status: NSObject {
    // 微博创建时间
    var creae_at : String?
    // 微博ID
    var id: Int = 0
    // 微博信息内容
    var text: String?
    // 微博来源
    var source: String?
    
    private var imageURLs: [NSURL]?
    
    var pic_urls: [[String:String]]? {
        didSet {
            imageURLs = [NSURL]()
            
            for dict in pic_urls! {
                let urlString = dict["thumbnail_pic"]!
                imageURLs?.append(NSURL(string: urlString)!)
            }
        }
    }
    
    var picURLs : [NSURL]? {
        return retweeted_status != nil ? retweeted_status?.imageURLs : imageURLs
    }
    
    var user: User?
    var retweeted_status: Status?
    static let properties = ["creae_at","id","text","source","imageURLs","pic_urls","user","retweeted_status"]
    
    init(dict: [String: AnyObject]) {
        super.init()
        for key in Status.properties {
            if dict[key] == nil || key == "user" || key == "retweeted_status"{
                continue
            }
            setValue(dict[key], forKey: key)
        }
        
        if let userDict = dict["user"] as? [String : AnyObject] {
            user = User(dict : userDict)
        }
        
        if let retweetedDict = dict["retweeted_status"] as? [String : AnyObject]{
            retweeted_status = Status(dict: retweetedDict)
        }
        
    }
    
    override var description : String {
        let dict = dictionaryWithValuesForKeys(Status.properties)
        return "\(dict)"
    }
    
    class func loadStatus(since_id:Int, fnisished:(statuses:[Status]?,error:NSError?) -> ()) {
        assert(shareAccount != nil, "必须登录之后才能访问网络")
        
        var params = ["access_token" : shareAccount!.access_token]
        
        if since_id > 0 {
            params["since_id"] = "\(since_id)"
        }
        
        
        NetworkTools.shareNetworkTools().GET(WB_Home_Timeline_URL, parameters: params, success: { (_, JSON) -> Void in
            
            if let array = JSON["statuses"] as? [[String: AnyObject]] {
                let list = parseJsonDict(array)
//                fnisished(statuses: list)
                cacheWebImages(list, finished: fnisished)
                return
            }
            fnisished(statuses: nil, error: nil)
            

            
            
            
            }) { (_, error) -> Void in
                print(error)
                fnisished(statuses: nil, error: error)
        }
    }
    
    
    private class func cacheWebImages(list: [Status], finished: (statuses: [Status]?, error: NSError?) -> ()) {
        
        // 0. 定义调度组
        let group = dispatch_group_create()
        
        // 1. 遍历数组
        for s in list {
            // 2. 判断 imageURLs 是否有内容
            if s.picURLs == nil || s.picURLs!.isEmpty {
                continue
            }
            
            // 2. 进一步遍历 imageURLs 的数组，缓存数组中的图片
            for url in s.picURLs! {
                // 1> 进入组，后续的 block 代码会受 group 监听
                dispatch_group_enter(group)
                
                // 用 sdwebimage 缓存图片 downloadImageWithURL 是 SDWebImage 核心的图像下载函数
                SDWebImageManager.sharedManager().downloadImageWithURL(url, options: SDWebImageOptions(rawValue: 0), progress: nil, completed: { (_, _, _, _, _)  in
                    
                    // 代码执行到此，说明图片已经被缓存完成
                    // 2> 离开组
                    dispatch_group_leave(group)
                })
            }
        }
        
        // 3> 监听群组调度执行
        dispatch_group_notify(group, dispatch_get_main_queue()) {
            // 完成回调
            finished(statuses: list, error: nil)
        }
    }
    

    
    private class func parseJsonDict(array:[[String: AnyObject]]) -> [Status] {
    
        var arrayM = [Status]()
        for dict in array {
            arrayM.append(Status(dict: dict))
        }
       return arrayM
    }
    
    

}





























